import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import styles from './PermissionManagement.module.css';

const API_BASE = 'http://localhost:3001/api';

interface Role {
    id: number;
    name: string;
    code: string;
    description: string;
    status: string;
}

interface Permission {
    id: number;
    name: string;
    code: string;
    resource: string;
    action: string;
    type: string;
    description: string;
}

interface RolePermission {
    roleId: number;
    permissionId: number;
}

const PermissionManagement: React.FC = () => {
    const { t } = useTranslation();
    const [activeTab, setActiveTab] = useState<'roles' | 'permissions' | 'assign'>('roles');
    const [roles, setRoles] = useState<Role[]>([]);
    const [permissions, setPermissions] = useState<Permission[]>([]);
    const [selectedRole, setSelectedRole] = useState<Role | null>(null);
    const [rolePermissions, setRolePermissions] = useState<number[]>([]);
    const [loading, setLoading] = useState(false);

    // 加载角色列表
    const loadRoles = async () => {
        try {
            // 尝试多种token存储方式
            let token = localStorage.getItem('token') ||
                localStorage.getItem('accessToken');

            // 如果还是没有token，尝试从user信息构造token（临时解决方案）
            if (!token) {
                const userStr = localStorage.getItem('user');
                if (userStr) {
                    try {
                        const user = JSON.parse(userStr);
                        if (user.id) {
                            token = `mock-jwt-token-${user.id}`;
                            console.log('从user信息构造token:', token);
                        }
                    } catch (e) {
                        console.error('解析user信息失败:', e);
                    }
                }
            }

            console.log('使用的token:', token ? `${token.substring(0, 30)}...` : '未找到token');

            if (!token) {
                alert('未找到认证令牌，请重新登录');
                return;
            }

            const response = await fetch(`${API_BASE}/permissions/roles`, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
            if (response.ok) {
                const result = await response.json();
                console.log('角色数据:', result);
                setRoles(result.data || []);
            } else {
                const errorData = await response.json().catch(() => ({ error: '未知错误' }));
                console.error('加载角色失败:', response.status, errorData);
                alert(`加载角色失败: ${errorData.error || '未知错误'}`);
            }
        } catch (error) {
            console.error('加载角色失败:', error);
            alert(`加载角色失败: ${error instanceof Error ? error.message : '网络错误'}`);
        }
    };

    // 加载权限列表
    const loadPermissions = async () => {
        try {
            // 尝试多种token存储方式
            let token = localStorage.getItem('token') ||
                localStorage.getItem('accessToken');

            // 如果还是没有token，尝试从user信息构造token
            if (!token) {
                const userStr = localStorage.getItem('user');
                if (userStr) {
                    try {
                        const user = JSON.parse(userStr);
                        if (user.id) {
                            token = `mock-jwt-token-${user.id}`;
                        }
                    } catch (e) {
                        // 忽略错误
                    }
                }
            }

            if (!token) {
                return;
            }

            const response = await fetch(`${API_BASE}/permissions/permissions`, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
            if (response.ok) {
                const result = await response.json();
                console.log('权限数据:', result);
                setPermissions(result.data || []);
            } else {
                const errorData = await response.json().catch(() => ({ error: '未知错误' }));
                console.error('加载权限失败:', response.status, errorData);
            }
        } catch (error) {
            console.error('加载权限失败:', error);
        }
    };

    // 加载角色权限
    const loadRolePermissions = async (roleId: number) => {
        try {
            // 尝试多种token存储方式
            let token = localStorage.getItem('token') ||
                localStorage.getItem('accessToken');

            // 如果还是没有token，尝试从user信息构造token
            if (!token) {
                const userStr = localStorage.getItem('user');
                if (userStr) {
                    try {
                        const user = JSON.parse(userStr);
                        if (user.id) {
                            token = `mock-jwt-token-${user.id}`;
                        }
                    } catch (e) {
                        // 忽略错误
                    }
                }
            }

            if (!token) {
                return;
            }

            const response = await fetch(`${API_BASE}/permissions/roles/${roleId}/permissions`, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
            if (response.ok) {
                const data = await response.json();
                const permIds = (data.data || []).map((p: Permission) => p.id);
                setRolePermissions(permIds);
            }
        } catch (error) {
            console.error('加载角色权限失败:', error);
        }
    };

    useEffect(() => {
        loadRoles();
        loadPermissions();
    }, []);

    // 选择角色时加载其权限
    useEffect(() => {
        if (selectedRole) {
            loadRolePermissions(selectedRole.id);
        }
    }, [selectedRole]);

    // 保存角色权限
    const saveRolePermissions = async () => {
        if (!selectedRole) return;

        setLoading(true);
        try {
            // 尝试多种token存储方式
            let token = localStorage.getItem('token') ||
                localStorage.getItem('accessToken');

            // 如果还是没有token，尝试从user信息构造token
            if (!token) {
                const userStr = localStorage.getItem('user');
                if (userStr) {
                    try {
                        const user = JSON.parse(userStr);
                        if (user.id) {
                            token = `mock-jwt-token-${user.id}`;
                        }
                    } catch (e) {
                        // 忽略错误
                    }
                }
            }

            if (!token) {
                alert('未找到认证令牌，请重新登录');
                setLoading(false);
                return;
            }

            const response = await fetch(`${API_BASE}/permissions/roles/permissions`, {
                method: 'PUT',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    roleId: selectedRole.id,
                    permissionIds: rolePermissions
                })
            });

            if (response.ok) {
                const result = await response.json();
                alert(result.message || '权限分配成功！');
                // 重新加载权限，确保显示最新状态
                if (selectedRole) {
                    await loadRolePermissions(selectedRole.id);
                }
            } else {
                const error = await response.json();
                alert(`保存失败: ${error.error || '未知错误'}`);
            }
        } catch (error) {
            console.error('保存失败:', error);
            alert('保存失败，请重试');
        } finally {
            setLoading(false);
        }
    };

    // 切换权限选择
    const togglePermission = (permissionId: number) => {
        setRolePermissions(prev => {
            if (prev.includes(permissionId)) {
                return prev.filter(id => id !== permissionId);
            } else {
                return [...prev, permissionId];
            }
        });
    };

    // 按资源分组权限
    const permissionsByResource = permissions.reduce((acc, perm) => {
        if (!acc[perm.resource]) {
            acc[perm.resource] = [];
        }
        acc[perm.resource].push(perm);
        return acc;
    }, {} as Record<string, Permission[]>);

    return (
        <div className={styles.container}>
            <div className={styles.header}>
                <h1>权限角色管理</h1>
                <div className={styles.tabs}>
                    <button
                        className={activeTab === 'roles' ? styles.active : ''}
                        onClick={() => setActiveTab('roles')}
                    >
                        角色管理
                    </button>
                    <button
                        className={activeTab === 'permissions' ? styles.active : ''}
                        onClick={() => setActiveTab('permissions')}
                    >
                        权限列表
                    </button>
                    <button
                        className={activeTab === 'assign' ? styles.active : ''}
                        onClick={() => setActiveTab('assign')}
                    >
                        权限分配
                    </button>
                </div>
            </div>

            <div className={styles.content}>
                {activeTab === 'roles' && (
                    <div className={styles.section}>
                        <h2>角色列表</h2>
                        <div className={styles.tableContainer}>
                            <table className={styles.table}>
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>角色名称</th>
                                        <th>角色代码</th>
                                        <th>描述</th>
                                        <th>状态</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {roles.length === 0 ? (
                                        <tr>
                                            <td colSpan={5} style={{ textAlign: 'center', padding: '20px', color: '#999' }}>
                                                暂无角色数据
                                            </td>
                                        </tr>
                                    ) : (
                                        roles.map(role => (
                                            <tr key={role.id}>
                                                <td>{role.id}</td>
                                                <td>{role.name}</td>
                                                <td>{role.code}</td>
                                                <td>{role.description}</td>
                                                <td>
                                                    <span className={role.status === 'active' ? styles.active : styles.inactive}>
                                                        {role.status === 'active' ? '启用' : '禁用'}
                                                    </span>
                                                </td>
                                            </tr>
                                        ))
                                    )}
                                </tbody>
                            </table>
                        </div>
                    </div>
                )}

                {activeTab === 'permissions' && (
                    <div className={styles.section}>
                        <h2>权限列表</h2>
                        <div className={styles.permissionsGrid}>
                            {Object.entries(permissionsByResource).map(([resource, perms]) => (
                                <div key={resource} className={styles.resourceGroup}>
                                    <h3>{resource}</h3>
                                    <div className={styles.permissionsList}>
                                        {perms.map(perm => (
                                            <div key={perm.id} className={styles.permissionItem}>
                                                <div className={styles.permissionCode}>{perm.code}</div>
                                                <div className={styles.permissionName}>{perm.name}</div>
                                                <div className={styles.permissionDesc}>{perm.description}</div>
                                                <div className={styles.permissionType}>
                                                    <span className={styles.badge}>{perm.type}</span>
                                                    <span className={styles.badge}>{perm.action}</span>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {activeTab === 'assign' && (
                    <div className={styles.section}>
                        <h2>权限分配</h2>
                        <div className={styles.assignContainer}>
                            <div className={styles.roleSelector}>
                                <label>选择角色：</label>
                                <select
                                    value={selectedRole?.id || ''}
                                    onChange={(e) => {
                                        const role = roles.find(r => r.id === parseInt(e.target.value));
                                        setSelectedRole(role || null);
                                    }}
                                    className={styles.select}
                                >
                                    <option value="">请选择角色</option>
                                    {roles.map(role => (
                                        <option key={role.id} value={role.id}>
                                            {role.name} ({role.code})
                                        </option>
                                    ))}
                                </select>
                            </div>

                            {selectedRole && (
                                <div className={styles.permissionsSelector}>
                                    <h3>为角色 "{selectedRole.name}" 分配权限</h3>
                                    {selectedRole.id === 1 && (
                                        <div style={{
                                            padding: '12px',
                                            backgroundColor: '#e3f2fd',
                                            border: '1px solid #2196f3',
                                            borderRadius: '4px',
                                            marginBottom: '16px',
                                            color: '#1976d2'
                                        }}>
                                            <strong>提示：</strong>管理员角色自动拥有所有权限，无需手动分配。即使修改，系统也会自动恢复为所有权限。
                                        </div>
                                    )}
                                    <div className={styles.permissionsGrid}>
                                        {Object.entries(permissionsByResource).map(([resource, perms]) => (
                                            <div key={resource} className={styles.resourceGroup}>
                                                <h4>{resource}</h4>
                                                <div className={styles.checkboxGroup}>
                                                    {perms.map(perm => (
                                                        <label key={perm.id} className={styles.checkboxLabel}>
                                                            <input
                                                                type="checkbox"
                                                                checked={rolePermissions.includes(perm.id)}
                                                                onChange={() => {
                                                                    // 管理员角色不允许修改权限
                                                                    if (selectedRole.id !== 1) {
                                                                        togglePermission(perm.id);
                                                                    }
                                                                }}
                                                                disabled={selectedRole.id === 1}
                                                                style={{
                                                                    cursor: selectedRole.id === 1 ? 'not-allowed' : 'pointer',
                                                                    opacity: selectedRole.id === 1 ? 0.6 : 1
                                                                }}
                                                            />
                                                            <span style={{
                                                                opacity: selectedRole.id === 1 ? 0.7 : 1
                                                            }}>{perm.name} ({perm.code})</span>
                                                        </label>
                                                    ))}
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                    <div className={styles.actions}>
                                        <button
                                            onClick={saveRolePermissions}
                                            disabled={loading || selectedRole.id === 1}
                                            className={styles.btnPrimary}
                                            style={{
                                                opacity: selectedRole.id === 1 ? 0.6 : 1,
                                                cursor: selectedRole.id === 1 ? 'not-allowed' : 'pointer'
                                            }}
                                            title={selectedRole.id === 1 ? '管理员角色无需手动分配权限' : ''}
                                        >
                                            {loading ? '保存中...' : selectedRole.id === 1 ? '管理员自动拥有所有权限' : '保存权限分配'}
                                        </button>
                                        <button
                                            onClick={() => {
                                                if (selectedRole) {
                                                    loadRolePermissions(selectedRole.id);
                                                }
                                            }}
                                            className={styles.btnSecondary}
                                        >
                                            重置
                                        </button>
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

export default PermissionManagement;

